//拿到URL中的参数
function getParam(name)
{
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return decodeURI(r[2]); return null;
}


//验证邮箱
function checkEmail(email)
{
	var emailReg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	if(emailReg.test(email))
	{
		return true;
	}else{
		return false;
	}
}
//验证电话
function checkPhone(phone)
{
	var mobileReg=/^1[358]{1}[0-9]{1}[0-9]{8}$/;
	if(!checkPhone && !mobileReg.test(phone))
	{
        return false;
	}else{
        return true;
	}
}


function getCurrDate(){
	var date=new Date();
	var month=date.getMonth()+1;
	if(month<10)
	{
		month = "0"+month;
	}
	var day=date.getDate();
	if(day<10)
	{
		day = "0"+day;
	}

	return date.getFullYear()+'-'+month+'-'+day+' '+'23:59:59';
}
//取一个月前的日期
function getOldDate(){
	var date=new Date();
	date.setDate(date.getDate()-30);

	var month=date.getMonth()+1;
	if(month<10)
	{
		month = "0"+month;
	}
	var day=date.getDate();
	if(day<10)
	{
		day = "0"+day;
	}

	return date.getFullYear()+'-'+month+'-'+day+' '+'00:00:00';
}



function IsPC()  {
	var userAgentInfo = navigator.userAgent;
	var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
	var flag = true;
	for (var v = 0; v < Agents.length; v++) {
		if (userAgentInfo.indexOf(Agents[v]) > 0)
		{
			flag = false; break;
		}
	}
	return flag;
}


//显示文件格式
window.makeText = function(str,num) {
	if(str && num)
	{
		var length = str.length;
		if(length>num)
		{
			str = str.substring(0,num) + "...";
		}
		var re = new RegExp("((?:http|https|ftp|mms|rtsp)://(&(?=amp;)|[A-Za-z0-9\./=\?%_~@&#:;\+\-])+)", "ig");
		str=str.replace(re,"<a href='$1' target='_blank'>$1</a>");
		return str;
	}else{
		return "";
	}
};

var language=getLanguage();
var contextPath=getContextPath();


function topLoading()
{
    if(!item || item.length==0){
        var item = $("<div id='topLoadingDiv' class='top_loading'><img border='0' src='/images/loading.gif'/></div>");
        item.appendTo("body");
    }
	document.getElementById("topLoadingDiv").className="top_loading";
	$("#topLoadingDiv").offset({ top: (document.body.clientHeight-32)/2, left: (document.body.clientWidth-32)/2 });
}

function topLoaded()
{
	$('#topLoadingDiv').remove();
	if(document.getElementById("topLoadingDiv")!='null' && document.getElementById("topLoadingDiv")!=undefined)
	{
		document.getElementById("topLoadingDiv").className="top_loaded";
	}
}


function setFormBeanValue(formId,bean)
{
	var form=document.forms[formId];
	for(var key in bean)
	{
		if(form[key]!=undefined){form[key].value=bean[key];}
	}
}
function setFormBeanDisabled(formId,bean,flag)
{
	var form=document.forms[formId];
	if(bean!=null && bean!=undefined)
	{
		for(var key in bean){if(form[key]!=undefined){form[key].disabled=flag;}}
	}else{
		$("input[type!=button][type!=submit][type!=reset]",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.disabled=flag;}
		});
		$("select",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.disabled=flag;}
		});
		$("textarea",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.disabled=flag;}
		});
	}
}
function setFormBeanReadonly(formId,bean,flag)
{
	var form=document.forms[formId];
	if(bean!=null && bean!=undefined)
	{
		for(var key in bean){if(form[key]!=undefined){form[key].readonly=flag;}}
	}else{
		$("input[type!=button][type!=submit][type!=reset]",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.readonly=flag;}
		});
		$("select",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.readonly=flag;}
		});
		$("textarea",$(form)).each(function()
		{
			if(this.name!=null && this.name!=''){this.readonly=flag;}
		});
	}
}

function serializeForm(formName)
{
	var form=document.forms[formName];
	var params=new Object();
	$("input[type!=button][type!=submit][type!=reset]",$(form)).each(function()
	{
		if(this.name!=null && this.name!='')
		{
			if(this.type=="checkbox" || this.type=="radio")
			{
				if(this.checked){params[this.name]=this.value;}
			}else{
				params[this.name]=this.value;
			}
		}
	});
	$("select",$(form)).each(function()
	{
		if(this.name!=null && this.name!=''){params[this.name]=this.value;}
	});
	$("textarea",$(form)).each(function()
	{
		if(this.name!=null && this.name!=''){params[this.name]=this.value;}
	});
	return params;
}
Array.prototype.remove = function(index)
{
	if(isNaN(index)||(index>=this.length)||(index<0)) return false;
	this.splice(index,1);
	return true;
}
Array.prototype.del=function(n){if(n<0){return this;}else{return this.slice(0,n).concat(this.slice(n+1,this.length));}}
Array.prototype.indexOf = function(value)
{
	for(var i=0;i<this.length;i++)
	{
		if(typeof(value)=="function")
		{
			if(value.equals(this[i])) return i;
		}else if(value==this[i]){
			return i;
		}
	}
	return -1;
}
Array.prototype.contains = function(value){return this.indexOf(value)>=0;}
Array.prototype.clear = function(){while(this.length>0) this.remove(this.length-1);}
Array.prototype.add = function(index,value)
{
	if(value==undefined)
	{
		this.put(index);
	}else{
		var len = this.length;
		this.push(this[len-1]);
		for(var i=len-1;i>index;i--) {this[i] = this[i-1];}
		this[index] = value;
	}
}
Array.prototype.put = function(value)
{
	if(!this.contains(value)) this.push(value);
}
Array.prototype.circle = function(degressive)
{
	if(degressive)
	{
		var a = this[0];
		for(var i=0;i<this.length-1;i++){ this[i] = this[i+1];}
		this[this.length-1] = a;
	}else{
		var a = this[this.length-1];
		for(var i=this.length-1;i>0;i--){ this[i] = this[i-1];}
		this[0] = a;
	}
}
/**
 * 兼容IE9以下的placeholder属性显示
 * 注意在加载列表数据之前要先调$('[placeholder]').focusin() 清空placeholder的显示值,否在IE9下显把它当作参数提交
 * 数据加载完成之后,可调用$('[placeholder]').focusout() 重新显示placeholder;
 */
function placeholder()
{
	if(!placeholderSupport())
	{
		// 判断浏览器是否支持 placeholder
		$('[placeholder]').focusin(function()
		{
			var input = $(this);
			if (input.val() == input.attr('placeholder'))
			{
				input.val('');
				input.removeClass('placeholder');
			}
		}).focusout(function()
		{
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('placeholder'))
			{
				input.addClass('placeholder');
				input.val(input.attr('placeholder'));
			}
		}).focusout();
	};
}
function placeholderSupport(){return 'placeholder' in document.createElement('input');}

function toMaxFractionDigits(value,digits)
{
	value=value+"";
	if(value.lastIndexOf(".")!=-1 && value.length-value.lastIndexOf(".")>digits)
	{
		value=value.substring(0,value.lastIndexOf(".")+digits+1);
	}
	return value;
}

function initSelectOptions()
{
	$("select").each(function()
	{
		var isWithBlank=false;
		var url=null,select=null,opt=null;
		if($(this).attr("isWithBlank"))
		{
			isWithBlank=$(this).attr("isWithBlank").toLowerCase()=="true"?true:false;
		}

		if($(this).attr("data"))
		{
			select=this;
			url=$(this).attr("data");
			if(url.indexOf(getContextPath()+"/")==-1)
			{
				url=getContextPath()+url;
			}
		}else if($(this).attr("apiId"))
		{
			select=this;
			url=getApi($(this).attr("apiId"));
		}
		if(url!=null)
		{
			if($(this).attr("params"))
			{
				if(url.indexOf("?")==-1)
				{
					url=url+"?";
				}
				url=url+$(this).attr("params");
			}

			if(sessionStorage.getItem(url)==undefined || sessionStorage.getItem(url)=="")
			{
				$.getJSON(url,{},function(resultBean)
				{
					if(resultBean.success)
					{
						for(var i=select.options.length;i>=0;i--) select.options.remove(i);

						if(isWithBlank)
						{
							opt=document.createElement('option');
							select.options.add(opt);
							opt.value="";
							opt.innerHTML="";
						}
						for(var key in resultBean.data)
						{
							opt=document.createElement('option');
							select.options.add(opt);
							opt.value=key;
							opt.innerHTML=resultBean.data[key];
						}

						if($(select).attr("defaultValue"))
						{
							selectOption(select,$(select).attr("defaultValue"));
						}

						sessionStorage.setItem(url,JSON.stringify(resultBean));
					}
				});
			}else{
				var resultBean=jQuery.parseJSON(sessionStorage.getItem(url));

				for(var i=select.options.length;i>=0;i--) select.options.remove(i);

				if(isWithBlank)
				{
					opt=document.createElement('option');
					select.options.add(opt);
					opt.value="";
					opt.innerHTML="";
				}
				for(var key in resultBean.data)
				{
					opt=document.createElement('option');
					select.options.add(opt);
					opt.value=key;
					opt.innerHTML=resultBean.data[key];
				}

				if($(select).attr("defaultValue"))
				{
					selectOption(select,$(select).attr("defaultValue"));
				}
			}
		}
	});
}

function checkPermission()
{
	var userPermissionIdSet= window.top.getUserPermissionIdSet();
	$("a,input[type='button'],button").each(function()
	{
		if($(this).attr("permissionId") && !userPermissionIdSet.contains($(this).attr("permissionId")))
		{
			$(this).attr("disabled",true);
			$(this).attr("disabled","disabled");
			$(this).addClass("l-btn-disabled");
			$(this).attr("href","#");
			$(this).attr("onclick","");
			$(this).attr("ondblclick","");
		}
	});
}

function initAutoComplete()
{
	var property;
	$("input[type='text']").each(function()
	{
		var cls=this.className;
		if(cls!=undefined && cls!="" && cls.indexOf("topAutoComplete")>-1)
		{
			property=this.name;
			var id=this.id;
			if(id==undefined || id=="")
			{
				id=property;
				$(this).attr("id",id);
			}
			$(this).attr("accessKey",$(this).attr("formBeanName")+"."+$(this).attr("fromBeanProperty"));
			$(this).attr("lang",$(this).attr("where"));
			$(this).attr("autocomplete",false);
			$(this).attr("onkeyup","autoComplete(event,'"+property+"','"+$(this).attr("recordsSize")+"');");
			$(this).attr("onblur","autoCompleteLossFocus('"+property+"');");

			var html="<div id='"+id+"_div' style='position:absolute;display:none;margin:0px;padding:0px;' onkeypress=\"autoCompleteKeyPress(event,'"+property+"')\"></div>";
			$("#"+id).before(html);
		}
	});
}

function getLanguage(){return "";}

function getContextPath()
{
	var localObj = window.location;
	return localObj.protocol+"//"+localObj.host+"/"+localObj.pathname.split("/")[1];
}

function isIE(){return window.navigator.userAgent.indexOf("MSIE")>=1;}

function getJsParameter(jsFileName,parameterName)
{
	var keyName = new RegExp(jsFileName+"(\\?(.*))?$");
	var jsTags=document.getElementsByTagName("script");
	for (var i = 0;i < jsTags.length; i++)
	{
		var jsTag = jsTags[i];
		if (jsTag.src&&jsTag.src.match(keyName))
		{
			var obj = jsTag.src.match(keyName)[2];
			if (obj&&(paramStr = obj.match(/([^&=]+)=([^=&]+)/g)))
			{
				for (var l = 0; l < paramStr.length; l++)
				{
					param = paramStr[l];
					var params = param.match(/([^&=]+)=([^=&]+)/);
					if (params)
					{
						if(params[1]==parameterName)
						{
							return params[2];
						}
					}
				}
			}
		}
	}
	return "";
}

function reloadJS(id,url)
{
	var oldjs = document.getElementById(id);
	if(oldjs) oldjs.parentNode.removeChild(oldjs);
	var scriptObj = document.createElement("script");
	scriptObj.src = url;
	scriptObj.type = "text/javascript";
	scriptObj.id   = id;
	document.getElementsByTagName("head")[0].appendChild(scriptObj);
}

function handleAjaxRequest(xmlHttpRequest, status,resultBean)
{
	var requestRedirectUri= xmlHttpRequest.getResponseHeader("REQUEST_REDIRECT_URI");
	if(requestRedirectUri==null || requestRedirectUri=="null"){requestRedirectUri="";}
	if(resultBean!=undefined && !resultBean.success)
	{
		if(resultBean.code=="NO_SESSION")
		{
			alert("用户未登录或用户会话信息已过期");
			window.top.location.href=resultBean.data+"?url="+document.location.href
			return false;
		}else if(resultBean.code=="NO_PERMISSION")
		{
			alert("用户无此功能的权限");
			return false;
		}else if(resultBean.code=="UNAUTHORIZATION_FOR_VISITOR")
		{
			alert("您是未验证的访客");
			window.top.location.href=requestRedirectUri+"?url="+document.location.href
			return false;
		}else if(resultBean.code=="EXCEPTION")
		{
			alert("系统出现错误");
			return false;
		}
	}

	var ajaxRequestChecking = xmlHttpRequest.getResponseHeader("AJAX_REQUEST_CHECKING");
	if(ajaxRequestChecking!=null)
	{
		if(ajaxRequestChecking=="NO_SESSION")
		{
			if(requestRedirectUri==null)
			{
				requestRedirectUri=getContextPath();
			}
			alert("用户未登录或用户会话信息已过期");
			window.top.location.href=resultBean.data+"?url="+document.location.href
			return false;
		}else if(ajaxRequestChecking=="NO_PERMISSION"){
			alert("用户无此功能的权限");
			return false;
		}else if(ajaxRequestChecking=="UNAUTHORIZATION_FOR_VISITOR"){
			alert("您是未验证的访客");
			window.top.location.href=requestRedirectUri+"?url="+document.location.href
			return false;
		}else if(ajaxRequestChecking=="EXCEPTION"){
			alert("系统出现错误");
			return false;
		}
	}
	return true;
}

function selectOption(obj,value)
{
	for(i=0;i<obj.length;i++)
	{
		if(obj[i].value==value)
		{
			obj[i].selected=true;
			break;
		}
	}
}

function countDown(countDownId,times)
{
	var countDownObj=document.getElementById(countDownId);
	var dtArr=countDownObj.innerHTML.split(":");
	var seconds=parseInt(dtArr[0],10)*60+parseInt(dtArr[1],10);
	if(seconds>0)
	{
		seconds=seconds-1;
	}
	countDownObj.innerHTML=parseInt(seconds/60,10)+":"+seconds%60;
	setTimeout("countDown('"+countDownId+"',"+times+")",times);
}

function cursorGoTo(event,fieldName)
{
	if(event.keyCode==13)
	{
		var fields=document.getElementsByName(fieldName);
		if(fields){fields[0].focus();}
	}
}

function getObjectPosition(obj)
{
	var left=obj.offsetLeft;
	var top=obj.offsetTop;
	var height=obj.offsetHeight;
	var width=obj.offsetWidth-18;
	while(obj=obj.offsetParent)
	{
		top+=obj.offsetTop;
		left+=obj.offsetLeft;
	}
	var arr=new Array();
	arr[0]=left;
	arr[1]=top;
	arr[2]=height;
	arr[3]=width;
	return arr;
}

function trimString(obj)
{
	obj.value=obj.value.replace(new RegExp("(^[\\s]*)|([\\s]*$)", "g"), "");
}

function canUpload(filePath,maxSize,warningMessage)
{
	var size=getFileSize(filePath);
	if(size>maxSize)
	{
		alert(warningMessage);
		return false;
	}
	return true;
}

function selectAddOption(select,value,text)
{
	var opt=document.createElement('option');
	select.options.add(opt);
	opt.value=value;
	opt.innerHTML=text;
}

function setupSelectOptions(select,dataMap,isWithBlank)
{
	if(select instanceof String )
	{
		select=document.getElementById(select);
	}
	isWithBlank=isWithBlank==undefined?false:isWithBlank;

	for(var i=select.options.length;i>=0;i--) select.options.remove(i);

	var opt;
	if(isWithBlank)
	{
		opt=document.createElement('option');
		select.options.add(opt);
		opt.value="";
		opt.innerHTML="";
	}
	if(dataMap==null){return;}
	for(var key in dataMap)
	{
		opt=document.createElement('option');
		select.options.add(opt);
		opt.value=key;
		opt.innerHTML=dataMap[key];
	}
}

function getFormFieldsStr(form,expFields)
{
	if(expFields==null){expFields="recordId";}
	var queryCondition="";
	$("input[type!=button][type!=submit][type!=reset][name!=null][name!='']",$(form)).each(function()
	{
		if(expFields.indexOf(this.name)!=-1){return;}
		if(this.value=='') return;
		if(queryCondition!=""){queryCondition+="&";}
		queryCondition+=this.name+"="+this.value;
	});
	$("select[name!=null][name!='']",$(form)).each(function()
	{
		if(expFields.indexOf(this.name)!=-1){return;}
		if(this.value=='') return;
		if(queryCondition!=""){queryCondition+="&";}
		queryCondition+=this.name+"="+this.value;
	});
	$("textarea[name!=null][name!='']",$(form)).each(function()
	{
		if(expFields.indexOf(this.name)!=-1){return;}
		if(this.value=='') return;
		if(queryCondition!=""){queryCondition+="&";}
		queryCondition+=this.name+"="+this.value;
	});
	return queryCondition
}

function anchorFocus(target,event)
{
	if(event.keyCode==13 && target.value!="")
	{
		var obj=document.getElementById(target.value);
		if(obj){document.location.href="#"+target.value;}
	}
}

function getFileSize(filePath)
{
	var image=new Image();
	image.dynsrc=filePath;
	return image.fileSize;
}


function calculateAge(date)
{
	var dt=new Date();
	if(date==null || date=='' || date.length!=10) return 0;
	var age=dt.getFullYear()-parseInt(date.substring(0,4),10)-1;
	if(parseInt(date.substring(5,7),10)<(dt.getMonth()+1))
	{
		age=age+1;
	}else{
		if (parseInt(date.substring(8, 10),10) <= dt.getDate())
		{
			age = age + 1;
		}
	}
	return age;
}

function pauseMillisecond(n)
{
	var startTime=(new Date()).getTime();
	var endTime,times;
	while(true)
	{
		endTime=(new Date()).getTime();
		times=endTime-startTime;
		if(times>=n){break;}
	}
}

function removeHTML(html)
{
	html = html.replace(/<.*?>/g,"");
	html = html.replace(/[ | ]*n/g,'n');
	html = html.replace(/n[s| | ]*r/g,'n');
	return html;
}

function getParentForm(target)
{
	while(true)
	{
		target=target.parentNode;
		if(target.tagName.toLowerCase()=="form") return target;
	}
}

function putBeanValueToFormSub(formField,tagName,value)
{
	tagName=tagName.toLowerCase();
	if(tagName=="input" && formField.type.toLowerCase()!="checkbox"  && formField.type.toLowerCase()!="radio")
	{
		formField.value=value;
	}else if(tagName=="input" && formField.type.toLowerCase()=="checkbox")
	{
		if(formField.value=value){formField.checked=true;}
	}else if(tagName=="input" && formField.type.toLowerCase()=="radio")
	{
		if(formField.value==value){formField.checked=true;}
	}else if(tagName=="textarea")
	{
		formField.value=value;
	}else if(tagName=="select")
	{
		selectOption(formField,value);
	}else{
		formField.value=value;
		formField.innerHTML=value;
	}
}

function putBeanValueToForm(bean,formName)
{
	if(!bean || !formName) return false;
	var form=document.forms[formName];
	if(!form) return false;
	var formField=null,tagName=null;
	for(var key in bean)
	{
		formField=form[key];
		if(!formField)
		{
			if($("#"+key)!=undefined)
			{
				formField=$("#"+key);
			}else{
				continue;
			}
		}
		tagName=formField.tagName;
		if(tagName)
		{
			putBeanValueToFormSub(formField,tagName,bean[key]);
		}else{
			for(var i=0;i<formField.length;i++)
			{
				putBeanValueToFormSub(formField[i],formField[i].tagName,bean[key]);
			}
		}
	}
	return true;
}

function screenInfo()
{
	var  s = "";
	s += "\r\n网页可见区域宽："+ document.body.clientWidth;
	s += "\r\n网页可见区域高："+ document.body.clientHeight;
	s += "\r\n网页可见区域宽："+ document.body.offsetWidth  +" (包括边线的宽)";
	s += "\r\n网页可见区域高："+ document.body.offsetHeight +" (包括边线的宽)";
	s += "\r\n网页正文全文宽："+ document.body.scrollWidth;
	s += "\r\n网页正文全文高："+ document.body.scrollHeight;
	s += "\r\n网页被卷去的高："+ document.body.scrollTop;
	s += "\r\n网页被卷去的左："+ document.body.scrollLeft;
	s += "\r\n屏幕分辨率的高："+ window.screen.height;
	s += "\r\n屏幕分辨率的宽："+ window.screen.width;
	s += "\r\n屏幕可用工作区高度："+ window.screen.availHeight;
	s += "\r\n屏幕可用工作区宽度："+ window.screen.availWidth;
	alert(s);
}

function goMethod(method,event)
{
	if(event!=undefined && event!=null && event!="")
	{
		if(event.keyCode==13)
		{
			eval(method+"()");
		}
	}else{
		eval(method+"()");
	}
}


$.fn.serializeObject = function()
{
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

/****************************************************************************************************************************
 * 业务公共
 */
var USER_MOBILE = "userMobile";
var USER_PASS = "password";

function exit(){
    $.ajax({
        type: "POST",
        url: '/user/userexit',   //提交地址
        dataType: "json",
        success: function(data){
            if(data && data.success){
                if(window.localStorage){
                    var storage=window.localStorage;
                    //写入用户手机号字段
                    storage[USER_MOBILE] = "";
                    //写入用户密码字段
                    storage[USER_PASS] = "";
                    layer.msg('退出成功');
                    setTimeout(function() {
                        window.location.href = "/";  //返回主页
                    }, 2000)
                }
            }
        }
    });
}

